package com.knife.oauth.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.knife.oauth.app.service.IamUserRoleService;
import com.knife.oauth.domain.entity.IamMemberRole;
import com.knife.oauth.domain.entity.IamRole;
import com.knife.oauth.domain.entity.IamUser;
import com.knife.oauth.infra.mapper.IamMemberRoleMapper;
import com.knife.oauth.infra.mapper.IamRoleMapper;
import com.knife.oauth.infra.mapper.IamUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2022年02月20日 星期日 11:33 下午
 * @description
 * @since 1.0
 */
@Service
public class IamUserRoleServiceImpl implements IamUserRoleService {

    @Autowired
    private IamUserMapper iamUserMapper;


    @Autowired
    private IamMemberRoleMapper iamMemberRoleMapper;

    @Autowired
    private IamRoleMapper iamRoleMapper;


    @Override
    public IamUser selectByUserName(String loginName) {
        return iamUserMapper.selectOne(new QueryWrapper<IamUser>().eq("login_name", loginName));
    }

    @Override
    public List<IamMemberRole> listIamMemberRoleByUserName(String loginName) {
        IamUser iamUser = iamUserMapper.selectOne(new QueryWrapper<IamUser>().eq("login_name", loginName));
        List<IamMemberRole> iamMemberRoles = iamMemberRoleMapper.selectList(new QueryWrapper<IamMemberRole>().eq("user_id", iamUser.getId()));
        List<IamRole> iamRoles = iamRoleMapper.selectList(null);
        HashMap<Long, IamRole> iamRoleHashMap = new HashMap<>(iamRoles.size());
        iamRoles.forEach(item->iamRoleHashMap.put(item.getId(),item));
        for (IamMemberRole iamMemberRole : iamMemberRoles) {
            IamRole iamRole = iamRoleHashMap.get(iamMemberRole.getRoleId());
            iamMemberRole.setRoleName(iamRole.getName());
            iamMemberRole.setRoleCode(iamRole.getCode());
        }
        return iamMemberRoles;
    }
}
